package com.easy.consumer;

import com.alibaba.fastjson.JSON;
import com.easy.common.exception.ServiceException;
import com.easy.common.util.SKRequest;
import com.easy.common.util.SYS;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class SKConsumer {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 监听秒杀请求队列
     * @param message
     */
    @RabbitListener(queues=SYS.SK_QUEUE)
    public void comsumerMessage(String message){
        try {
            ValueOperations vos = redisTemplate.opsForValue();
            SKRequest skRequest = JSON.parseObject(message, SKRequest.class);
            Integer skgoodsid = skRequest.getSkgoodsid();
            String sk_key = "sk" + skgoodsid;//redis中存儲的秒殺商品的key對應val是數量
            //获取分布式锁
            while (!vos.setIfAbsent(SYS.SK_LOCK_KEY, "")) ;
            //检查活动是否开启
            //检查用户是否已经抢购  ---  用户允许抢购的数量是可以在钱够商品中设置的
            //商品数量是否还够
            if (vos.get(sk_key) != null && Integer.parseInt(vos.get(sk_key).toString()) > 0) {
                //先扣数量
                redisTemplate.opsForValue().decrement(sk_key);
            } else {
                //秒殺沒有數量，轉發死信隊列
                rabbitTemplate.convertAndSend(SYS.SK_EXCHANGE, SYS.SK_DLX_ROUTING_KEY, message);
            }
            //扣完數量放開鎖
            redisTemplate.delete(SYS.SK_LOCK_KEY);
            //生成订单--操作數據庫--Dubbo

        }catch(Exception e){
            //失败，将消息转到死信队列
            rabbitTemplate.convertAndSend(SYS.SK_EXCHANGE, SYS.SK_DLX_ROUTING_KEY, message);
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 监听死信队列  秒杀失败的消息队列
     * @param message
     */
    @RabbitListener(queues=SYS.SK_DLX_QUEUE)
    public void comsumerDLXMessage(String message){
        //在秒杀记录表中添加一条秒杀失败的记录
    }
}
